﻿// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED!
// YOU MAY USE THIS CODE: HOWEVER THIS GRANTS NO FUTURE RIGHTS.
// see https://spsearchbestbetsmigration.codeplex.com/license and https://spsearchbestbetsmigration.codeplex.com/ for further details and license information

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace SPSearchBestBetsMigration
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void rdoScopeFarm_CheckedChanged(object sender, EventArgs e)
        {
            SetRDOVisibility();
        }

        private void rdoScopeWebApp_CheckedChanged(object sender, EventArgs e)
        {
            SetRDOVisibility();
        }

        private void rdoScopeSiteColl_CheckedChanged(object sender, EventArgs e)
        {
            SetRDOVisibility();
        }

        void SetRDOVisibility()
        {
            if (rdoScopeFarm.Checked)
            {
                this.cboWebApps.Visible = false;
                this.lblWebApps.Visible = false;
                this.cboSiteColl.Visible = false;
                this.lblSiteColl.Visible = false;
            }
            if (rdoScopeWebApp.Checked)
            {
                this.cboWebApps.Visible = true;
                this.lblWebApps.Visible = true;
                this.cboSiteColl.Visible = false;
                this.lblSiteColl.Visible = false;
            }
            if (rdoScopeSiteColl.Checked)
            {
                this.cboWebApps.Visible = true;
                this.lblWebApps.Visible = true;
                this.cboSiteColl.Visible = true;
                this.lblSiteColl.Visible = true;
            }
        }

        private void cboWebApps_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Get selected Web App
            string webAppUrl = this.cboWebApps.SelectedItem.ToString();
            PopulateSiteCollections(webAppUrl, this.cboSiteColl);
        }

        private void PopulateSiteCollections(string webAppUrl, ComboBox cbo) {

            // Load the site collections for the selected Web Application
            cbo.Items.Clear();
            foreach (SPWebApplication webApp in SPWebService.ContentService.WebApplications)
            {
                string webUrl = webApp.GetResponseUri(SPUrlZone.Default).AbsoluteUri;
                if (webUrl == webAppUrl)
                {
                    foreach (SPSite site in webApp.Sites)
                    {
                        string fullSiteUrl = site.Url;
                        cbo.Items.Add(fullSiteUrl);
                        site.Close();
                    }
                    break;
                }
            }
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            //Populate the Web APplication from the Current Farm
            PopulateWebApplications(this.cboWebApps);
            SetRDOVisibility();

            //Populate the Current folder Path where this App is run.
            string directory = AppDomain.CurrentDomain.BaseDirectory;
            this.txtMigFilePath.Text = directory + "migration.mig";

            CheckFilePathExists(this.txtMigFilePath.Text);
        }

        void PopulateWebApplications(ComboBox cbo)
        {
            // Load Web Applications
            cbo.Items.Clear();
            foreach (SPWebApplication webApp in SPWebService.ContentService.WebApplications)
            {
                string webUrl = webApp.GetResponseUri(SPUrlZone.Default).AbsoluteUri;
                cbo.Items.Add(webUrl);
            }

            //If only 1 web app, load site collections automatically
            if (cbo.Items.Count == 1)
            {
                cbo.SelectedIndex = 0;
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            this.rdoScopeFarm.Select();
            PopulateWebApplications(this.cboWebApps);
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            string oldName = this.txtMigFilePath.Text;
            if (oldName.Length == 0) return;

            int pos = oldName.LastIndexOf("\\");
            if (pos <= 0) return;

            oldName = oldName.Substring(pos+1);

            string folderpath = "";
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            DialogResult dr = fbd.ShowDialog();

            if (dr == DialogResult.OK)
            {
                folderpath = fbd.SelectedPath;
                if (oldName.Length == 0)
                {
                    this.txtMigFilePath.Text = folderpath + "\\migration.mig";
                }
                else
                {
                    this.txtMigFilePath.Text = folderpath + "\\" + oldName;
                }
            }
            CheckFilePathExists(this.txtMigFilePath.Text);
        }

        private void txtMigFilePath_Leave(object sender, EventArgs e)
        {
            CheckFilePathExists(this.txtMigFilePath.Text);
        }

        void CheckFilePathExists(string fullPath)
        {
            //Check if file exists
            if (System.IO.File.Exists(fullPath))
            {
                this.txtMigFilePath.ForeColor = Color.DarkGreen;
                this.btnImport.Enabled = true;
            }
            else
            {
                this.txtMigFilePath.ForeColor = Color.Red;
                this.btnImport.Enabled = false;
            }
        }

        private void btnOpenPath_Click(object sender, EventArgs e)
        {
            string filePath = this.txtMigFilePath.Text;
            int pos = filePath.LastIndexOf("\\");
            if (pos > 0)
            {
                string folderPath = filePath.Substring(0, pos);
                if (System.IO.Directory.Exists(folderPath))
                {
                    System.Diagnostics.Process.Start("explorer.exe", folderPath);
                }
            }
            else
            {
                MessageBox.Show("Folder Path is invalid", "Migration Folder Path", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            bool bProceed = false;
            string filePath = this.txtMigFilePath.Text;

            //Check if file exists
            if (System.IO.File.Exists(filePath))
            {

                DialogResult btnRes = MessageBox.Show("The Migration File will be overwritten", "Migration File Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (btnRes == DialogResult.Yes)
                {
                    bProceed = true;
                }
                else
                {
                    bProceed = false;
                }
            }
            else
            {
                bProceed = true;
            }

            if (bProceed == true) {

                // Begin the Export
                if (this.rdoScopeFarm.Checked)
                {
                    SearchMigration.ExportSearchBestBets(filePath);
                }
                else
                {

                    if (this.rdoScopeWebApp.Checked)
                    {
                        string webAppUrl = this.cboWebApps.SelectedItem.ToString();
                        SearchMigration.ExportSearchBestBets(SearchMigration.MigScope.WebApp, filePath, webAppUrl);
                    }
                    else
                    {
                        string siteCollUrl = this.cboSiteColl.SelectedItem.ToString();
                        SearchMigration.ExportSearchBestBets(SearchMigration.MigScope.SiteColl, filePath, siteCollUrl);
                    }
                }

                //Refresh file status
                CheckFilePathExists(filePath);

                MessageBox.Show("Success :)", "Migration File Exported Successfully", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            string filePath = this.txtMigFilePath.Text;

            //Check if file exists
            if (!System.IO.File.Exists(filePath))
            {
                MessageBox.Show("The Migration File does not exist. Unable to proceed.", "Migration File Non-existent", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                try
                {
                    SearchMigration.ImportKeywords(filePath, this.cbxRemoveOld.Checked);

                    MessageBox.Show(this,"Success :)", "Migration File Imported Successfully", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, ex.Message, "Migration File Import Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

        }

        private void cbxRemoveOld_CheckedChanged(object sender, EventArgs e)
        {
            if (cbxRemoveOld.Checked)
                lblNoCleanUpWarning.Visible = false;
            else
                lblNoCleanUpWarning.Visible = true;
        }


    }
}
